<template>
<div class="login-bg">
  <div class="login-row">
      
      <div class="login-title">
          {{$config.system.APP_NAME}}
      </div>
      <el-form
      ref="usernameLoginForm" 
      :model="loginForm"
      :rules="rules"
      hide-required-asterisk
      class="login-form"
    >
      <el-form-item prop="tenant">
          <el-select v-model="loginForm.tenant" filterable placeholder="请选择组织">
              <template #prefix>
                  <el-icon><School /></el-icon>
              </template>    
              <el-option
              v-for="item in organizationSearchOptions"
              :key="item.organizationId"
              :label="item.organizationName"
              :value="item.organizationId"
              >
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" clearable maxlength="50" placeholder="请输入用户名" :prefix-icon="UserFilled" @keyup.enter="submitLogin" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" show-password maxlength="50" v-model="loginForm.password" placeholder="请输入密码" :prefix-icon="Lock" @keyup.enter="submitLogin" />
      </el-form-item>
      <el-form-item prop="kaptcha">
        <el-input ref="kaptchaInput" v-model="loginForm.kaptcha" maxlength="4" style="width:50%" placeholder="请输入验证码" @keyup.enter="submitLogin">
          <template #prefix>
            <el-icon style="height:inherit;">
              <IconExtraGuard />
            </el-icon>    
          </template>
          
        </el-input>
        <img class="codeimg" :src="captchaImg" @click="getCaptchaImg" alt v-if="captchaImg" />
      </el-form-item>
      <el-form-item class="remember">
        <el-checkbox v-model="loginForm.rememberme" label="记住密码" size="large" title="有效期90天"></el-checkbox>
      </el-form-item>
    </el-form>
    <el-button type="primary" class="login-btn" @click="submitLogin">登&nbsp;录</el-button>
  </div>
  <el-footer v-if="$config.system.FOOTER.SHOW" :class="{'beian':$config.system.BEIAN}"><bottom-footer :beian="$config.system.BEIAN" /></el-footer>
</div>
</template>
<script setup>
import topRoutes from '@/router/topRoute'
import authApi from '@/api/auth'
import orgApi from '@/api/organization'
import BottomFooter from '@/views/Layout/BottomFooter'
import { ElLoading } from 'element-plus'
import 'element-plus/es/components/loading/style/css'
import {reactive,ref,onMounted} from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {message} from '@/plugin/elementplus'
import IconExtraGuard from '~icons/extra/guard';
import { UserFilled,
  Lock } from '@element-plus/icons-vue'
const store=useStore()
const router = useRouter()
const loginForm=reactive({
    username:store.state.user.rememberme.username,
    password:store.state.user.rememberme.password,
    tenant:store.state.user.rememberme.tenant,
    kaptcha:'',
    rememberme:!!store.state.user.rememberme.username,
    signature:''
})
const organizationSearchOptions=ref([])
const rules= reactive({
        tenant: [
          {
            required: true,
            message: '请选择组织',
            trigger: 'change',
          },
        ],
        username: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'change',
          },
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'change',
          },
        ],
        kaptcha: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'change',
          }
        ],
      })
const usernameLoginForm=ref(null)
const kaptchaInput=ref(null)
const captchaImg=ref(null)
if(loginForm.rememberme){
    onMounted(()=>{
        kaptchaInput.value.focus()
    })    
}
const getCaptchaImg=function(){
    captchaImg.value=null
    authApi.getKaptcha().then(d=>{
        if(!!d && d.code=='200'){
            captchaImg.value='data:image/png;base64,'+d.data.img
            loginForm.signature=d.data.signature
        }
    })
}
const getUserMenus=function(){
  return authApi.getUserMenus().then(d=>{
    console.log(d)
    if(!!d && d.code=='200'){
      store.commit('setLeftMenu',{menuList:d.data})
      store.commit('setTopMenu',{menuList:topRoutes})
      return Promise.resolve()
    }
    else{
      return Promise.reject()
    }
  }).catch(()=>{
    return Promise.reject()
  })
};
const getUserPermissions=function(){
  return authApi.getUserPermissions().then(d=>{
    console.log(d)
    if(!!d && d.code=='200'){
      store.commit('setPermissions',{permissions:d.data || []})
      return Promise.resolve()
    }
    else{
      return Promise.reject()
    }
  }).catch(()=>{
    return Promise.reject()
  })
};
const queryOrganization=function(){
  orgApi.queryOrganizations().then(d=>{
      if(!!d && d.code=='200'){
          organizationSearchOptions.value=d.data || []
      }
  })
}
queryOrganization()
const submitLogin=function(){
    usernameLoginForm.value.validate(valid=>{
        if(valid){
           const loading = ElLoading.service({
                lock: true,
                text: '正在加载',
                // background: 'rgba(0, 0, 0, 0.7)',
            })
            authApi.login(loginForm).then(d=>{
                console.log(d)
                if(!!d && d.code=='200'){
                    store.commit('setToken',d.data)
                    store.commit('setRememberme',loginForm)
                    Promise.all([getUserMenus(),getUserPermissions()]).then(()=>{
                        store.commit('setUser',{token:d.data.token,name:d.data.user.username,expire:d.data.expire})
                        router.push('/')
                        loading.close()
                    })
                    .catch(()=>{
                        loading.close()
                    })
                }
                else{
                    message({
                        message: d.message,
                        type: 'warning',
                    })
                    loading.close()
                }
            }).catch(()=>{
                loading.close()
            })
        }
    })
}
getCaptchaImg()
</script>

<style scoped>
.login-title{
    font-size: 30px;
    margin-top:10px;
    margin-bottom: 10px;
    font-weight: 500;
}
.login-bg{
    text-align: center;
    height: 100%;
    width: 100%;
    background-image: url("../../assets/img/login_bg.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size:cover;
}

 .login-bg:before{
    content:'';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}
.codeimg 
{
    width:110px;
    margin-left:calc(50% - 110px);
}
.login-btn{
    width: 100%;
    line-height: 38px;
}
.login-row{
    margin-top:-100px;
    vertical-align: middle;
    display: inline-block;
    background-color: #fff;
    padding:0 15px 15px;
    border-radius: 5px;
    width: 380px;
    /* position: absolute;
    top:50%;
    transform: translateY(-50%); */
}
.remember{
    margin-top: -5px;
    margin-bottom: 10px;
}
:deep(.el-input__inner),.el-checkbox.el-checkbox--large :deep(.el-checkbox__label),.login-btn,.codeimg{
    height: 40px;
    line-height: 40px;
    font-size: 14px;
}
:deep(.el-checkbox__inner)::after{
    left:5px;
    top:2px;
}
.el-checkbox.el-checkbox--large :deep(.el-checkbox__inner){
   height: 16px; 
   width: 16px; 
}
.el-select{
  width:100%
}
.el-footer{
  padding:0;
  height:40px;
  line-height:40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  color:#fff;
  /* background-color: #f0f0f0d0; */
}
.el-footer.beian{
  height:50px;
  line-height:inherit;
}
@media screen and (max-width: 500px) {
   .login-row{
        width: calc(100% - 30px);
    }
}
@media screen and (min-width:501px) and (max-width: 900px) {
  .login-row{
        margin-top:0;
        width: 70%;
        min-width: 380px;
    }
}
</style>